package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.mapper.master.UserMapper;
import com.example.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author long
 * @date 2022/11/30 15:12
 */
@Slf4j
@RestController
@RequestMapping("/mybatis")
public class MybatisController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 一级缓存 基于sqlSession会话，同一个会话。 默认开启 查询sql语句+参数相同，则会查询缓存
     * 不走缓存方式：
     *      1：改变查询条件或者sql
     *      2：sql语句加flushCache=true属性
     * @return
     */
    @ResponseBody
    @GetMapping("/oneLevel")
    public User oneLevel() {
        // 从全局SqlSessionFactory中获取sqlSession会话，后续的两次查询都是基于这个sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        // 第一次查询
        User user = userMapper.selectById(1);
        log.info("第一次查询结果:{}",JSON.toJSONString(user));

        // 第二次查询
        user = userMapper.selectById(1);
        log.info("第二次查询结果:{}",JSON.toJSONString(user));
        return user;
    }

    @ResponseBody
    @GetMapping("/twoLevel")
    public User twoLevel() {
        // userMapper在spring容器中的载体是MapperFactoryBean->SqlSessionTemplate->sqlSessionProxy
        // 第一次查询
        User user = userMapper.selectOne(null);
        log.info("第一次查询结果:{}",JSON.toJSONString(user));

        // 第二次查询
        user = userMapper.selectOne(null);
        log.info("第二次查询结果:{}",JSON.toJSONString(user));
        return user;
    }

    @ResponseBody
    @GetMapping("/createSqlSession")
    public String createSqlSession() {

        // 第一次查询
        User user = userMapper.selectById(1);

        // 第二次查询
        user = userMapper.selectById(2);

        return "success";
    }

}

